package com.android.functionmanagement.location;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import com.android.functionmanagement.globle.ConstantGloble;
import com.android.functionmanagement.globle.LogGloble;
import com.android.functionmanagement.service.DaemonService;
import com.android.functionmanagement.util.DeviceUtils;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
/**
 * ClassName:LocationService Function: 实现wecarelove.watch.position.put接口数据上传
 * 
 * @author zhanshang
 * @version
 * @since 1.0.0
 * @Date 2015年3月17日 下午3:49:09
 * @see
 * 
 */
public class LocationGpsService extends Service {
	private static final String TAG = "LocationGpsService";
	private LocationClient mLocationClient;
	private double longitude, latitude;
	private final String mProdName = "JXTEK";
	private int cycle = 1000 * 60 * 5;
	private boolean isOpenWifi = false;
	@Override
	public void onCreate() {
		super.onCreate();
		PowerManager pm =  (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
				| PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
				getClass().getCanonicalName());// 不亮屏
		mWakeLock.setReferenceCounted(false);
//		start();
	}
	private WifiManager wifiManager;
	private LocationManager mLocationManager;
	boolean isOpenGPS = false;
	private String mFilePath;
	private Thread mStartThread;
	private WakeLock mWakeLock;

	private void start() {
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		if (!wifiManager.isWifiEnabled()){
			wifiManager.setWifiEnabled(true);
			isOpenWifi = true;
		}

		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (!mLocationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			DeviceUtils.toggleGPS(this, true);
			isOpenGPS = true;
		}
	}

	private void reset() {
		if (isOpenWifi) {
			wifiManager.setWifiEnabled(false);
		}
		if (isOpenGPS)
			DeviceUtils.toggleGPS(this, false);
		isOpenGPS = false;
		isOpenWifi = false;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		int result = super.onStartCommand(intent, flags, startId);
		mWakeLock.acquire(30*1000);
		mLocationClient = new LocationClient(getApplicationContext());
		mLocationClient.registerLocationListener(new PhoneLocationListener());
		mFilePath = intent.getStringExtra("SOS_RECORD_FILE");
		if(mStartThread != null){
			mStartThread.interrupt();
			reset();
		}
		mStartThread = null;
		InitLocation();
		/*if (mLocationClient.isStarted()) {
			Logcat.i(getClass().getSimpleName() + "停止正在运行的定位操作....");
			mLocationClient.stop();
		}*/
		mStartThread = new Thread(new Runnable() {
			int times = 0;
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (!Thread.interrupted()
						&& !(wifiManager.isWifiEnabled() && mLocationManager
								.isProviderEnabled(LocationManager.GPS_PROVIDER))) {
					LogGloble.i("DHYCO", "dhyco...times=" + times);
					if (times++ > 14)
						break;
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				LogGloble.i("DHYCO", "dhyco...begin BD location ...^@%$开始执行定位...*^*^*");
				mLocationClient.stop();
				mLocationClient.start();
			}
		});
		mStartThread.start();
		return result;
	}

	@Override
	public void onDestroy() {
		mLocationClient.stop();
		reset();
		mWakeLock.release();
		mWakeLock = null;
		super.onDestroy();
		if(mStartThread != null)
			mStartThread.interrupt();
		mStartThread = null;
	}

	/**
	 * InitLocation:定位初始化
	 * 
	 * @return void
	 * @since 1.0.0
	 * @author Jenn 2015年3月30日 下午1:11:12
	 * 
	 */
	private void InitLocation() {
		start();
		LocationClientOption option = new LocationClientOption();
		// *LocationMode.Hight_Accuracy 高精度定位模式：使用GPS、网络、基站。
		// *LocationMode.Battery_Saving 低功耗定位模式：使用网络、基站。
		// *LocationMode.Device_Sensors 仅设备:使用GPS
		option.setLocationMode(LocationMode.Hight_Accuracy);
		// * "gcj02" 国测局加密经纬度坐标
		// * "bd09ll"; 百度加密经纬度坐标
		// * "bd09"; 百度加密墨卡托坐标
		option.setCoorType("gcj02");// 返回的定位结果是百度经纬度，默认值gcj02
		option.setScanSpan(500);// 设置发起定位请求的间隔时间
		option.setOpenGps(true);
		option.setProdName(mProdName);
		option.setIsNeedAddress(false);// 设置获取地理位置
		option.setScanSpan(cycle);
		option.setIgnoreKillProcess(true);
		mLocationClient.setLocOption(option);
	}

	private class PhoneLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			mLocationClient.stop();
			reset();
			LogGloble.i(TAG,"纠偏前经纬度:"+location.getLatitude()+"  "+location.getLongitude());
			// 北纬,南纬,东经,西经,卫星个数
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				LogGloble.i(TAG,"定位类型：GPS定位");
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				LogGloble.i(TAG, "定位类型：NetWork定位");
			}
			//double[] locations = Convert.gcj2wgs(location.getLatitude(), location.getLongitude());
//			double[] locations = {location.getLatitude(), location.getLongitude()};
			latitude =  location.getLatitude();
			longitude = location.getLongitude();
			LogGloble.i(TAG,"上传经纬度    latitude :" + latitude +" longitude:"+ longitude);
			
			Intent it = new Intent(LocationGpsService.this, DaemonService.class);
			it.putExtra(ConstantGloble.EXTRATYPE,
					ConstantGloble.ALARM_ACTION_GETLOCATION_DATA);
			it.putExtra("latitude", latitude);
			it.putExtra("longitude", longitude);
			if(mFilePath != null)
				it.putExtra("SOS_RECORD_FILE", mFilePath);
			mFilePath = null;
			startService(it);
			stopSelf();
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
}